local love = require 'love'
local fontHandler = require('assets-handler.font-handler')
local deck = require('scenes.deck')

local setColor = love.graphics.setColor
local drawRectangle = love.graphics.rectangle
local printg = love.graphics.print

local width = Width
local height = Height
local padding = Padding

local handCards = {}
local handCardsX = 0
local handCardsY = 0
local handCardsSelectedY = 0
local overlap = 0
local fontSize = 23
local widthHandCardsFiveEach = 0
local handCardsHeight = 0
local thisTurnSelectedCards = {}
local cardSelectedShadow = {}
local showIcon = false

local function init(maxHandCards)
    overlap = padding -- 重叠部分的宽度
    handCardsHeight = height / 6
    handCardsX = padding
    handCardsY = height - padding - handCardsHeight - height / 20 * 2
    handCardsSelectedY = handCardsY - height / 20
    widthHandCardsFiveEach = (width - padding * 2 + 4 * overlap) / 5 -- 计算最小宽度

    -- 避免动态扩容
    for i = 1, maxHandCards do
        handCards[i] = {
            x = 0,
            y = 0,
            width = 0,
            height = 0,
            number = 0,
            selected = false
        }
    end

    cardSelectedShadow = {
        x = 0,
        y = handCardsY,
        width = 0,
        height = handCardsHeight
    }
end

local function resetThisTurnSelectedCards()
    thisTurnSelectedCards = {}
end

-- 发牌
local function drawHnadCards(dealtCards, changeHandCards)
    if dealtCards == nil then return end

    local countHandCards = #dealtCards -- 动态调整手牌数，使其不超过拿到的牌数
    local widthHandCards = (width - padding * 2 + (countHandCards - 1) * overlap) / countHandCards -- 动态调整宽度

    -- 仅变化手牌时创建手牌序列
    if changeHandCards then
        changeHandCards = false
        -- 根据showIcon决定排序规则
        table.sort(dealtCards, function(a, b)
            if showIcon then
                -- 规则：个位数2、4在前，1、3在后；4在2前，3在1前；数值升序
                local a_mod = a % 10
                local b_mod = b % 10
                local priority = {[4] = 1, [2] = 2, [3] = 3, [1] = 4}

                if priority[a_mod] ~= priority[b_mod] then
                    return priority[a_mod] < priority[b_mod]
                end
                return a < b  -- 优先级相同则按数值升序
            else
                -- 正常排序：数值从小到大
                return a < b
            end
        end)

        -- 创建手牌信息
        if #dealtCards >= 5 then
            -- 紧凑显示
            for i = 1, #dealtCards do
                handCards[i] = {
                    x = handCardsX + (i - 1) * (widthHandCards - overlap),
                    y = handCardsY,
                    width = widthHandCards,
                    height = handCardsHeight,
                    number = dealtCards[i],
                    selected = false
                }
            end
        else
            -- 最小宽度为5张牌, 居中显示
            local widthHandCardsFive = widthHandCardsFiveEach * #dealtCards - overlap * (#dealtCards - 1)
            for i = 1, #dealtCards do
                handCards[i] = {
                    x = (width - widthHandCardsFive) / 2 + (i - 1) * (widthHandCardsFiveEach - overlap),
                    y = handCardsY,
                    width = widthHandCardsFiveEach,
                    height = handCardsHeight,
                    number = dealtCards[i],
                    selected = false
                }
            end
        end

        -- 销毁超出 dealtCards 长度的 handCards 元素
        for i = #handCards, #dealtCards + 1, -1 do
            handCards[i] = nil
        end
    end

    -- 判断是否选中并移动
    for i = 1, #dealtCards do
        if table.contains(thisTurnSelectedCards, handCards[i].number) then
            handCards[i].y = handCardsSelectedY
            handCards[i].selected = true
        else
            handCards[i].y = handCardsY
            handCards[i].selected = false
        end
    end

    -- 绘制手牌
    if #dealtCards > 0 then
        for _, hc in ipairs(handCards) do
            -- 绘制带黑色边框的长方形
            setColor(1, 1, 1)  -- 白色填充
            drawRectangle("fill", hc.x, hc.y, hc.width, hc.height)
            setColor(0, 0, 0)  -- 黑色边框
            drawRectangle("line", hc.x, hc.y, hc.width, hc.height)

            -- 绘制数字
            fontHandler.setFont(fontSize)
            if (hc.number % 10) % 2 == 1 then
                setColor(1, 0, 0)  -- 红色
            else
                setColor(0, 0, 0)  -- 黑色
            end
            printg(deck.getRank(hc.number), hc.x + padding, hc.y + padding)
            printg(deck.getSuit(hc.number), hc.x + padding, hc.y + hc.height * (1 - 0.618))
        end
    end
end

-- 框选功能
-- 框选状态变量
local selectionBox = {x1 = 0, y1 = 0, x2 = 0, y2 = 0, active = false}

-- 检测矩形是否与框选区域相交（包括边缘接触）
local function rectIntersectsSelection(card, offset)
    offset = offset or padding
    local boxMinX = math.min(selectionBox.x1, selectionBox.x2)
    local boxMaxX = math.max(selectionBox.x1, selectionBox.x2)
    local boxMinY = math.min(selectionBox.y1, selectionBox.y2)
    local boxMaxY = math.max(selectionBox.y1, selectionBox.y2)

    local cardMinX = card.x
    local cardMaxX = card.x + card.width - offset
    local cardMinY = card.y
    local cardMaxY = card.y + card.height

    -- 检测AABB碰撞（轴对齐边界框）
    return boxMinX < cardMaxX and
           boxMaxX > cardMinX and
           boxMinY < cardMaxY and
           boxMaxY > cardMinY
end

local function inArea(y)
    return y > handCardsSelectedY and y < height - padding
end

local function isPressed(x, y)
    selectionBox.x1 = x
    selectionBox.y1 = y
    selectionBox.x2 = x
    selectionBox.y2 = y
    selectionBox.active = true
end

local function isMoved(x, y)
    if selectionBox.active then
        selectionBox.x2 = x
        selectionBox.y2 = y
    end
end

local function isReleased()
    if selectionBox.active then
        selectionBox.active = false

        -- 临时存储框选结果
        local tempSelected = {}
        local tempSelectedCount = 0

        -- 收集框选结果
        local offset = padding
        for i, card in ipairs(handCards) do
            if i == #handCards then
                offset = 0
            end
            tempSelected[card.number] = rectIntersectsSelection(card, offset)
            if tempSelected[card.number] then
                tempSelectedCount = tempSelectedCount + 1
            end
        end

        -- 如果有选中的牌
        if tempSelectedCount > 0 then
            -- 检查框选的牌是否都已选中
            local allSelected = true
            for number, isSelected in pairs(tempSelected) do
                if isSelected and not table.contains(thisTurnSelectedCards, number) then
                    allSelected = false
                    break
                end
            end

            -- 根据规则更新选中状态
            if allSelected then
                -- 如果框选的牌都已经选中，则取消框选的牌的选中状态
                for number, isSelected in pairs(tempSelected) do
                    if isSelected then
                        table.remove_value(thisTurnSelectedCards, number)
                    end
                end
            else
                -- 否则，选中所有框选的牌
                for number, isSelected in pairs(tempSelected) do
                    if isSelected and not table.contains(thisTurnSelectedCards, number) then
                        table.insert(thisTurnSelectedCards, number)
                    end
                end
            end
        end
        return thisTurnSelectedCards or {}
    end
end

-- 辅助函数：从数组中移除指定值
function table.remove_value(array, value)
    for i = #array, 1, -1 do
        if array[i] == value then
            table.remove(array, i)
        end
    end
end

-- 辅助函数：检查数组是否包含指定值
function table.contains(array, value)
    for _, v in ipairs(array) do
        if v == value then
            return true
        end
    end
    return false
end

local function drawSelect()
    if selectionBox.active then
        local tempSelected = {}
        local minX = handCards[#handCards].x
        local maxX = 0

        -- 收集框选结果
       local offset = padding
        for i, card in ipairs(handCards) do
            if i == #handCards then
                offset = 0
            end
            tempSelected[card.number] = rectIntersectsSelection(card, offset)
            if tempSelected[card.number] then
                minX = math.min(minX, card.x)
                maxX = math.max(maxX, card.x)
            end
        end
        cardSelectedShadow.x = minX
        cardSelectedShadow.width = maxX - minX + handCards[1].width

        if cardSelectedShadow.width > 0 then
            setColor(0.5, 0.5, 0.5, 0.5)
            drawRectangle("fill", cardSelectedShadow.x, cardSelectedShadow.y, cardSelectedShadow.width, cardSelectedShadow.height)
        end
    end
end

return{
    init = init,
    resetThisTurnSelectedCards = resetThisTurnSelectedCards,
    drawHnadCards = drawHnadCards,
    inArea = inArea,
    getHandCards = function() return handCards end,
    toggleShowIcon = function() showIcon = not showIcon end,
    isPressed = isPressed,
    isMoved = isMoved,
    isReleased = isReleased,
    drawSelect = drawSelect
}